package utils

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/golang-jwt/jwt/v5"
	"time"
)

type Client1 struct {
	ID                    int    `json:"id"`
	ClientName            string `json:"client_name"`
	ClientPhone           string `json:"client_phone"`
	ClientClassify        string `json:"client_classify"`
	Time                  string `json:"time"`
	ClientFollow          string `json:"client_follow"`
	PromoterId            int    `json:"promoter_id"`
	CommunityId           int    `json:"community_id"`
	DateBirth             string `json:"date_birth"`
	NativePlace           string `json:"native_place"`
	Address               string `json:"address"`
	Gender                string `json:"gender"`
	IdCard                string `json:"id_card"`
	Age                   int    `json:"age"`
	Nation                string `json:"nation"`
	HealthyCondition      string `json:"healthy_condition"`
	MaritalStatus         string `json:"marital_status"`
	PoliticsStatus        string `json:"politics_status"`
	Children              string `json:"children"`
	Like                  string `json:"like"`
	EducationBackground   string `json:"education_background"`
	PhysicalExamination   string `json:"physical_examination"`
	Faith                 string `json:"faith"`
	NotEat                string `json:"not_eat"`
	Occupation            string `json:"occupation"`
	Unit                  string `json:"unit"`
	OnJob                 string `json:"on_job"`
	OwnHouse              string `json:"own_house"`
	Counselor             string `json:"counselor"`
	Company               string `json:"company"`
	Recreation            string `json:"recreation"`
	Investment            string `json:"investment"`
	GeneralSituation      string `json:"general_situation"`
	SpecificCircumstance  string `json:"specific_circumstance"`
	SubmissionTime        string `json:"submission_time"`
	Money                 string `json:"money"`
	EmergencyContactOne   string `json:"emergency_contact_one"`
	EmergencyContactTwo   string `json:"emergency_contact_two"`
	InterestPoint         string `json:"interest_point"`
	Network               string `json:"network"`
	PresentationCondition string `json:"presentation_condition"`
	OneMeet               string `json:"one_meet"`
	Insight               string `json:"insight"`
	Audit                 int    `json:"audit"`
}

type UserClaims struct {
	UserInfo Client1
	jwt.RegisteredClaims
}

func UserToken(userInfo Client1) (string, error) {
	jwt_key := []byte(beego.AppConfig.String("jwt_key1"))
	token_hour, _ := beego.AppConfig.Int64("token_hour")
	hour_duration, _ := time.ParseDuration(fmt.Sprintf("%dh", token_hour))
	// Create claims with multiple fields populated
	claims := UserClaims{
		userInfo,
		jwt.RegisteredClaims{
			// A usual scenario is to set the expiration time relative to the current time
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(hour_duration)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
			Issuer:    "zhxj",
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString(jwt_key)
	return tokenString, err
}

func VerifyUserToken(tokenString string) (Client1, error) {
	var userInfo Client1
	jwt_key := beego.AppConfig.String("jwt_key1")
	token, err := jwt.ParseWithClaims(tokenString, &MyClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(jwt_key), nil
	}, jwt.WithLeeway(5*time.Second))

	if claims, ok := token.Claims.(*UserClaims); ok && token.Valid {
		userInfo = claims.UserInfo
		return userInfo, nil
	} else {
		return userInfo, err
	}
}
